//
//  MJHaddViewController.m
//  PhoneNumber_20
//
//  Created by dllo on 15/11/21.
//  Copyright © 2015年 mjh. All rights reserved.
//

#import "MJHaddViewController.h"
#import "MJHLTView.h"
#import "MJHCoreDate.h"
#define WIDTH self.view.frame.size.width
#import "LSBGetDegress.h"
#import "UIImageView+Tranform3D.h"

@interface MJHaddViewController ()<BMKMapViewDelegate, BMKGeoCodeSearchDelegate>
{
    bool isGeoSearch;
}
@property (nonatomic, strong)MJHLTView *nameView;
@property (nonatomic, strong)MJHLTView *sexView;
@property (nonatomic, strong)MJHLTView *numView;
@property (nonatomic, strong)MJHLTView *phoneView;
@property (nonatomic, strong)MJHLTView *qqView;
@property (nonatomic, strong)MJHLTView *addressView;
@property (nonatomic, strong)MJHCoreDate *manager;


@end

@implementation MJHaddViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 100, self.view.frame.size.width, 200)];
    self.imageView.center = self.view.center;
    self.imageView.image = [UIImage imageNamed:@"1.png"];
    [self.view addSubview:self.imageView];
    
    
    [LSBGetDegress getDegressWithBlock:^(CMAccelerometerData *latestAcc, NSError *error) {
        if (latestAcc.acceleration.z*-1 >0.0 && latestAcc.acceleration.z*-1 <= 1.0) {
            [_imageView setRotation:80*latestAcc.acceleration.y];
        }
        else if (latestAcc.acceleration.y < 0.0&&latestAcc.acceleration.y >= -1.0)
        {
            [_imageView setRotation:80 - ( 80*latestAcc.acceleration.z*-1)];
            NSLog(@"------------%f",80*latestAcc.acceleration.z*-1);
        }
        
    }];

    self.view.backgroundColor = [UIColor whiteColor];
    self.nameView = [[MJHLTView alloc]initWithFrame:CGRectMake(0, 70, WIDTH, 40 )];
    [self.view addSubview:self.nameView];
    self.nameView.myTextField.text = self.person.name;
    self.nameView.myLabel.text =@"姓名";
    
    self.sexView = [[MJHLTView alloc]initWithFrame:CGRectMake(0, 110, WIDTH, 40 )];
    [self.view addSubview:self.sexView];
    self.sexView.myLabel.text =@"性别";
    self.sexView.myTextField.text = self.person.sex;

    
    self.numView = [[MJHLTView alloc]initWithFrame:CGRectMake(0, 150, WIDTH, 40 )];
    [self.view addSubview:self.numView];
    self.numView.myLabel.text =@"学号";
    self.numView.myTextField.text = [self.person.number stringValue];


    self.phoneView = [[MJHLTView alloc]initWithFrame:CGRectMake(0, 190, WIDTH, 40 )];
    [self.view addSubview:self.phoneView];
    self.phoneView.myLabel.text =@"电话";
    self.phoneView.myTextField.text = [self.person.phone stringValue];


    self.qqView = [[MJHLTView alloc]initWithFrame:CGRectMake(0, 230, WIDTH, 40 )];
    [self.view addSubview:self.qqView];
    self.qqView.myLabel.text =@"QQ";
    self.qqView.myTextField.text = [self.person.qq stringValue];

    
    self.addressView = [[MJHLTView alloc]initWithFrame:CGRectMake(0, 270, WIDTH, 40 )];
    [self.view addSubview:self.addressView];
    self.addressView.myLabel.text =@"籍贯";
    self.addressView.myTextField.text = self.person.address;

    
    UIButton *addButton = [UIButton buttonWithType:UIButtonTypeSystem];
    addButton.frame = CGRectMake(60, 320, 100, 40);
    [addButton setTitle:@"添加" forState:UIControlStateNormal];
    [self.view addSubview:addButton];
    [addButton addTarget:self action:@selector(addbutton) forControlEvents:UIControlEventTouchUpInside];
   
    UIButton *editButton = [UIButton buttonWithType:UIButtonTypeSystem];
    editButton.frame = CGRectMake(180, 320, 100, 40);
    [editButton setTitle:@"修改" forState:UIControlStateNormal];
    [self.view addSubview:editButton];
    [editButton addTarget:self action:@selector(editButtonaaa) forControlEvents:UIControlEventTouchUpInside];

    self.mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 365, WIDTH, self.view.frame.size.height - 365)];
    [self.view addSubview:self.mapView];
    self.mapView.hidden = YES;
    
    self.geocodesearch = [[BMKGeoCodeSearch alloc]init];
    [self.mapView setZoomLevel:14];

    self.manager = [MJHCoreDate shareSingleTon];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"map" style:UIBarButtonItemStylePlain target:self action:@selector(aaaaaa)];
    
}
- (void)aaaaaa{
    self.mapView.hidden = NO;
    isGeoSearch = true;
    BMKGeoCodeSearchOption *geocodeSearchOption = [[BMKGeoCodeSearchOption alloc]init];
    //    geocodeSearchOption.city= @"山东";
    geocodeSearchOption.address = self.addressView.myTextField.text;
    BOOL flag = [_geocodesearch geoCode:geocodeSearchOption];
    if(flag)
    {
        NSLog(@"geo检索发送成功");
    }
    else
    {
        NSLog(@"geo检索发送失败");
    }
    
}
#pragma mark 点击空白处
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [super touchesBegan:touches withEvent:event];
    [self.nameView.myTextField resignFirstResponder];
    [self.qqView.myTextField resignFirstResponder];
    [self.addressView.myTextField resignFirstResponder];
    [self.phoneView.myTextField resignFirstResponder];
    [self.sexView.myTextField resignFirstResponder];
    [self.numView.myTextField resignFirstResponder];


}
//修改
- (void)editButtonaaa{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.manager.managedObjectContext];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == %@", self.person.name];
    [fetchRequest setPredicate:predicate];
    // Specify how the fetched objects should be sorted
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    for (Person *per in fetchedObjects) {
        per.name = self.nameView.myTextField.text;
        per.sex = self.sexView.myTextField.text;
        per.number = @([self.numView.myTextField.text integerValue]);
        per.phone =@([ self.phoneView.myTextField.text integerValue]);
        per.address = self.addressView.myTextField.text;
        per.qq = @([self.qqView.myTextField.text integerValue]);
    }
    NSLog(@"%ld",fetchedObjects.count);
    [self.manager saveContext];
    [self.navigationController popViewControllerAnimated:YES];
    
}
//添加
- (void)addbutton{
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.manager.managedObjectContext];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    NSLog(@"%@",self.nameView.myTextField.text);
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == %@", self.nameView.myTextField.text];
    [fetchRequest setPredicate:predicate];
    // Specify how the fetched objects should be sorted
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    NSLog(@"%ld",fetchedObjects.count);
    if (fetchedObjects.count != 0 || [self.nameView.myTextField.text isEqualToString:@""]) {
        
        
        UIAlertController *alrtcontroller = [UIAlertController alertControllerWithTitle:@"通知" message:@"用户已存在,是否修改?" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancela = [UIAlertAction actionWithTitle:@"返回" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alrtcontroller addAction:cancela];
        UIAlertAction *edita = [UIAlertAction actionWithTitle:@"修改" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self editButtonaaa];
        }];
        [alrtcontroller addAction:edita];
        [self presentViewController:alrtcontroller animated:YES completion:^{
            
        }];
    }else{
        Person *per = [[Person alloc]initWithEntity:entity insertIntoManagedObjectContext:self.manager.managedObjectContext];
        per.name = self.nameView.myTextField.text;
        per.sex = self.sexView.myTextField.text;
        per.number = @([self.numView.myTextField.text integerValue]);
        per.phone =@([ self.phoneView.myTextField.text integerValue]);
        per.address = self.addressView.myTextField.text;
        per.qq = @([self.qqView.myTextField.text integerValue]);
        [self.manager saveContext];
    }
        [self.navigationController popViewControllerAnimated:YES];
}



-(void)viewWillAppear:(BOOL)animated {
    [_mapView viewWillAppear];
    _mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    _geocodesearch.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
}

-(void)viewWillDisappear:(BOOL)animated {
    [_mapView viewWillDisappear];
    _mapView.delegate = nil; // 不用时，置nil
    _geocodesearch.delegate = nil; // 不用时，置nil
}
//根据anntation生成对应的View
- (BMKAnnotationView *)mapView:(BMKMapView *)view viewForAnnotation:(id <BMKAnnotation>)annotation
{
    NSString *AnnotationViewID = @"annotationViewID";
    //根据指定标识查找一个可被复用的标注View，一般在delegate中使用，用此函数来代替新申请一个View
    BMKAnnotationView *annotationView = [view dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
    if (annotationView == nil) {
        annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
        ((BMKPinAnnotationView*)annotationView).pinColor = BMKPinAnnotationColorRed;
        ((BMKPinAnnotationView*)annotationView).animatesDrop = YES;
    }
    
    annotationView.centerOffset = CGPointMake(0, -(annotationView.frame.size.height * 0.5));
    annotationView.annotation = annotation;
    annotationView.canShowCallout = TRUE;
    return annotationView;
}
- (void)onGetGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    array = [NSArray arrayWithArray:_mapView.overlays];
    [_mapView removeOverlays:array];
    if (error == 0) {
        BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
        item.coordinate = result.location;
        item.title = result.address;
        [_mapView addAnnotation:item];
        _mapView.centerCoordinate = result.location;
        NSString* titleStr;
        NSString* showmeg;
        
        titleStr = @"正向地理编码";
        showmeg = [NSString stringWithFormat:@"经度:%f,纬度:%f",item.coordinate.latitude,item.coordinate.longitude];
        
        UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:titleStr message:showmeg delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",nil];
        [myAlertView show];
    }
}

-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    array = [NSArray arrayWithArray:_mapView.overlays];
    [_mapView removeOverlays:array];
    if (error == 0) {
        BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
        item.coordinate = result.location;
        item.title = result.address;
        [_mapView addAnnotation:item];
        _mapView.centerCoordinate = result.location;
        NSString* titleStr;
        NSString* showmeg;
        titleStr = @"反向地理编码";
        showmeg = [NSString stringWithFormat:@"%@",item.title];
        
        UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:titleStr message:showmeg delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",nil];
        [myAlertView show];
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}





/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
